import React, {
    Component,
} from 'react';

import {
    StyleSheet,
    Text,
    View,
    Platform,
    FlatList,
    Dimensions,
    TouchableOpacity,
    Image,
    ScrollView,
    StatusBar,
    Linking,
    ActivityIndicator,
    DeviceEventEmitter,
    TextInput,
    NativeModules
} from 'react-native';

import AndroidModule from 'src/utils/AndroidConnent'
import HttpUtils from "../../utils/HttpUtils";
import HttpUrls from "../../utils/HttpUrls";
import Constant from '../../utils/Constant'//全局变量
import Header from "../../components/header";
import Loading from "../../utils/Loading";

import NoData from "../../utils/NoData";

const isIos = Platform.OS == 'ios';
const screenW = Dimensions.get('window').width;

let navigation

export default class ChooseAlreadyAuthorizePage extends Component {

    constructor(props) {
        super(props);
        this.state = {
            authorizeList: [],
            isRefresh: false,
            showFoot: 0, // 控制foot， 0：隐藏footer  1：已加载完成,没有更多数据   2 ：显示加载中
            pageNo: 1
        }
    }
    componentWillUnmount() {

    }

    componentDidMount() {
        this.refreshData()
    }

    render() {
        navigation = this.props.navigation
        return (
            <View style={styles.container}>
                <Header navigation={navigation} Title={'选择企业'} />
                <View style={{height:10}}></View>
                {this.renderList()}
            </View>
        )
    }

    renderList() {
        return (
            <View style={{ flex: 1 ,marginBottom: Constant.isIPhoneX ? Constant.bottomHeight : 0}}>
                <FlatList
                    data={this.state.authorizeList}
                    renderItem={this.renderItemView.bind(this)}
                    extraData={this.state}
                    ListFooterComponent={this.renderFooter.bind(this)}
                    onEndReached={this._onEndReached.bind(this)}
                    onEndReachedThreshold={0.2}
                    onRefresh={this.refreshData}
                    refreshing={this.state.isRefresh}
                    ListEmptyComponent={this.renderEmpty.bind(this)}
                />
                <Loading onRef={(ref) => (this.Loading = ref)} />
            </View>
        )
    }

    renderItemView({ item, index }) {

        return (
            <TouchableOpacity key={index}  activeOpacity={0.6}
                onPress={() => {
                    this.selectAuthorize(item)
                }}>

                <View style={styles.authorizeItemContainer} key={index}>
                    {/* 公司名称 */}
                    <Text style={styles.companyName}>{item.orgName}</Text>
                    {/* 经办人 */}
                    <Text style={styles.handlerbyperson}>经办人：{item.psnMobile}</Text>
                    {/* 授权状态 */}
                    <View style={styles.statusContainer}>
                        <Text style={styles.status}>{this.getstatus(item)}</Text>
                    </View>
                
                    <TouchableOpacity style={styles.cancelContainer}  onPress={() => {
                            this.selectAuthorize(item)
                                }}>
                                <Text style={styles.cancelTitle}>选择</Text>
                        </TouchableOpacity>

                    {
                        index != this.state.authorizeList.length-1
                        ?
                        <View style={styles.borderBottom} >
                        </View>
                        :
                        null
                    }
                  
               
                </View>
        
            </TouchableOpacity>
        )
    }

    getstatus(item){    
        if(item.authorizedStatus ==0){
            return '过期失效'
        }else if(item.authorizedStatus ==1){
            return '已授权'
        }else if(item.authorizedStatus ==2){
            return '授权中'
        }else if(item.authorizedStatus ==3){
            return '审批未通过'
        }else if(item.authorizedStatus ==4){
            return '已取消授权'
        }else{
            return '未确认'
        }
    }

    refreshData = () => {
        this.setState({
            isRefresh: true,
            pageNo: 1,
            authorizeList: []
        }, function () {
            this.getAuthorizeLists()
        })
    }

    getAuthorizeLists() {

        let param = {
            pageNo: this.state.pageNo,
            pageSize: 20,
            merchantId: Constant.userInfo.merchantId,
            authorizedStatus:[1]
        }
        HttpUtils.postRequest(HttpUrls.merchantAuthList, param)
            .then((result) => {

                let data = result.data
                if (data) {
                    let resultList = data.resultList
                    if(this.state.pageNo == 1){
                        let systemInfo={}
                        systemInfo.orgName='系统模板'
                        systemInfo.psnMobile='系统'
                        systemInfo.authorizedStatus='1'
                        systemInfo.orgId='0'
                        resultList.unshift(systemInfo);
                    }

                    if (resultList && resultList != null && resultList.length > 0) {

                        this.setState({
                            authorizeList: this.state.authorizeList.concat(resultList),
                            isRefresh: false,
                            showFoot: 1,
                        });
                        setTimeout(() => {
                            this.setState({
                                showFoot: resultList.length >= 20 ? 0 : 1,
                            })

                        }, 200);
                    } else {
                        this.setState({
                            showFoot: 1,
                            isRefresh: false,
                        });
                    }
                } else {
                    this.setState({
                        showFoot: 1,
                        isRefresh: false,
                    });
                }
            })
            .catch((error) => {

            });
    }


    renderEmpty() {
        return (
            <NoData Desc="暂无数据" style={{ marginTop: gREM(200) }} />
        )
    }

    renderFooter() {
        if (this.state.showFoot === 1) {
            return null;

        } else if (this.state.showFoot === 2) {
            return (
                <View style={styles.footer}>
                    <ActivityIndicator size="small" color="#999999" />
                    <Text style={styles.loadMoreTextStyle}>正在加载更多数据...</Text>
                </View>
            );
        } else if (this.state.showFoot === 0) {
            return null;
        }
    }



    _onEndReached() {
        //如果是正在加载中或没有更多数据了，则返回
        if (this.state.showFoot != 0) {
            return null;
        }

        //底部显示正在加载更多数据
        this.setState(
            {
                showFoot: 2,
                pageNo: this.state.pageNo + 1
            }, function () {
                this.getAuthorizeLists()
            });
    }

 
    selectAuthorize(item){
        let obj = {
            orgName: item.orgName,
            type:'chooseAuthorize',
            orgId:item.orgId,
        }
        DeviceEventEmitter.emit('commonEvent', obj)
        navigation.goBack()
    }

}

const styles = StyleSheet.create({

    container: {
        width: screenW,
        flex: 1,
        backgroundColor: '#f6f6f6',
        position:'relative'
    },

    authorizeManagerContainer:{
        marginTop:16,
        marginLeft:16,
        marginRight:16,
        height:48,
        width:screenW-32,
        backgroundColor:'#ffffff',
        alignItems:'center',
        flexDirection:'row',
        borderRadius:6,
    },

    authorizeTitle:{
        marginLeft:12,
        fontWeight: '400',
        fontSize: 16,
        color: '#333333'
    },

    addauthorizeTitle:{
        fontWeight: '400',
        fontSize: 16,
        color: '#333333',
        position:'absolute',
        right:42,
        fontWeight: '400',
        fontSize: 14,
        color: '#666666',

    },

    authoniceadd:{
        width:24,
        height:24,
        position:'absolute',
        right:12,
    },

    authorizeItemContainer:{
        height:100,
        marginLeft:16,
        marginRight:16,
        width:screenW-32,
        backgroundColor:'#ffffff',
        position:'relative',
    },

    companyName:{
        fontWeight: '400',
        fontSize: 16,
        color: '#333333',
        marginTop:16,
        marginLeft:12
    },

    handlerbyperson:{
        fontWeight: '400',
        fontSize: 14,
        color: '#999999',
        marginTop:6,
        marginLeft:12
    },

    statusContainer:{
        backgroundColor:'rgba(249,152,2,0.1)',
        width:42,
        height:16,
        alignItems:'center',
        justifyContent:'center',
        borderRadius:1,
        marginTop:6,
        marginLeft:12
    },

    status:{
        fontWeight: '500',
        fontSize: 8,
        color: '#F99802',
    },

    cancelContainer:{
        width:72,
        height:28,
        position:'absolute',
        right:12,
        top:26,
        alignItems:'center',
        justifyContent:'center',
        borderRadius:3,
        borderColor:'#E5E5E5',
        borderWidth:0.8,
    },

    cancelTitle:{
        fontWeight: '400',
        fontSize: 12,
        color: '#333333',
    },

    borderBottom:{
        borderBottomColor:'#E4E4E4',
        borderBottomWidth:1,
        marginLeft:12,
        marginRight:12,
        position:'absolute',
        bottom:0,
        width:screenW-32-24,
    },


    
    addauthorizeLayout:{
        marginLeft:15,
        marginRight:15,
        width:screenW-30,
        height:46,
        backgroundColor:'#FFE000',
        borderRadius:4,
        alignItems:'center',
        justifyContent:'center',
    },

    addTitle:{
        fontWeight: '500',
        fontSize: 15,
        color: '#222222',
    },

    footer: {
        flexDirection: 'row',
        height: 40,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#f6f6f6'
    },
    loadMoreTextStyle: {
        fontSize: 14,
        color: '#999999',
        marginStart: 10,
    },



})